package com.zmn.brs.config;

import com.zmn.brs.common.enums.RuleDroolsTypeEnum;
import com.zmn.brs.drools.bean.KieBaseTemplate;
import com.zmn.brs.model.entity.drools.RuleDrools;
import com.zmn.brs.model.entity.drools.RuleDroolsQuery;
import com.zmn.brs.services.interfaces.drools.RuleDroolsService;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.List;

/**
 * 类描述：Drools初始化配置类
 * @author zhangyao
 * @since 2021/05/26 15:58
 */
@Slf4j
@Configuration
public class DroolsAutoConfiguration {

    private static final String TAG = "Drools初始化";

    private static final String RULES_PATH = "src/main/resources/com/zmn/brs/drools/rules/monitor/";

    private static final String RULES_PATH_SUFFIX = ".drl";

    @javax.annotation.Resource
    private RuleDroolsService ruleDroolsService;

    @Bean
    public KieHelper kieHelper() {
        return new KieHelper();
    }

    @Bean
    @ConditionalOnMissingBean(KieFileSystem.class)
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        RuleDroolsQuery ruleDroolsQuery = RuleDroolsQuery.builder().type(RuleDroolsTypeEnum.BASE.getTypeId()).build();
        List<RuleDrools> ruleDrools = ruleDroolsService.listByQuery(ruleDroolsQuery);
        for (RuleDrools ruleDrool : ruleDrools) {
            kieFileSystem.write(RULES_PATH + ruleDrool.getName() + RULES_PATH_SUFFIX, ruleDrool.getRule());
        }
        /*for (Resource file : getRuleFiles()) {
            String path = file.getFile().getPath();
            path = path.substring(path.indexOf(RULES_PATH));
            // 以下drl文件不需加载，等工单监控和登陆、查询、导出的监控都转换成新的方式后，可以删除这几个drl文件，并移除这里的判断。
            if (path.indexOf("City.drl") > -1 || path.indexOf("Frequency.drl") > -1 || path.indexOf("OperationTime.drl") > -1
                    || path.indexOf("rules.drl") > -1 || path.indexOf("StaffRole.drl") > -1) {
                continue;
            }
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }*/
        return kieFileSystem;
    }

    private Resource[] getRuleFiles() throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
//        return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*/*.*");// 只加载RULES_PATH子级目录中的文件
        return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");// 加载RULES_PATH目录下的所有文件，包括子级目录中的文件
    }

//    @Bean
//    @ConditionalOnMissingBean(KieContainer.class)
    private KieContainer kieContainer() throws IOException {
        final KieRepository kieRepository = getKieServices().getRepository();

        kieRepository.addKieModule(new KieModule() {
            public ReleaseId getReleaseId() {
                return kieRepository.getDefaultReleaseId();
            }
        });

        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        Results results = kieBuilder.getResults();
        if (results.hasMessages(Message.Level.ERROR)) {
            log.error("[{}]，初始化Drools文件出错：{}", TAG, results.getMessages(Message.Level.ERROR));
        } else {
            log.error("[{}]，初始化Drools文件成功：{}", TAG, results.getMessages(Message.Level.INFO, Message.Level.WARNING));
        }
        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }

    @Bean
    @ConditionalOnMissingBean(KieBaseTemplate.class)
    public KieBaseTemplate kieBaseTemplate() throws IOException {
        long start = System.currentTimeMillis();
        KieBaseTemplate kieBaseTemplate = KieBaseTemplate.builder().kieBase(kieContainer().getKieBase()).build();
        log.info("[{}]，初始化Drools耗时：{}", TAG, System.currentTimeMillis() - start);
        return kieBaseTemplate;
    }

    @Bean
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }

    /*@Bean
    @ConditionalOnMissingBean(KieSession.class)
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }*/

}